package com.gitee.huanminabc.jcommon.file;

import com.gitee.huanminabc.jcommon.exception.CommonException;

import java.io.File;
import java.io.IOException;

/**
 * @description:
 * @author: huanmin
 * @create: 2025-04-03 11:54
 **/
public class FileTempUtil {

    /**
     *创建临时文件
     * @param prefix 前缀,
     * @param suffix 后缀
     * 比如前缀设置test,后缀设置.txt那么结果如下:
     * C:\Users\huanmin\AppData\Local\Temp\test9169400899030102146.txt
     * @return
     */
    public static File createTempFile(String prefix, String suffix) {
        String tempDirectoryPath = getTempDirectoryPath();
        String filePath= tempDirectoryPath + File.separator + prefix + suffix;
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                if (newFile) {
                    return  file;
                }else{
                    throw new RuntimeException("创建临时文件失败");
                }
            } catch (IOException e) {
                throw new CommonException(e);
            }
        }
        return file;
    }

    /**
     * 创建临时文件夹
     * @param dirName 文件夹名称
     *  比如test 那么结果如下: C:\Users\huanmin\AppData\Local\Temp\test7950942266666786431
     * @return
     */
    public static File createTempDirectory(String dirName) {
        String tempDirectoryPath = getTempDirectoryPath();
        File file = new File(tempDirectoryPath + File.separator + dirName);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    //获取临时目录地址
    public static String getTempDirectoryPath() {
        return System.getProperty("java.io.tmpdir");
    }
    //通过prefix判断临时目录是否存在
    public static boolean isTempDirectory(String prefix) {
        File file = new File(getTempDirectoryPath());
        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    if (file1.getName().startsWith(prefix)) {
                        return true;
                    }
                }
            }else {
                return false;
            }
        }
        return false;
    }
}
